import os
from easyprocess import EasyProcess


def replace_file(filename_relative_to_repo):
    filename_relative_to_root = os.path.join("repo", filename_relative_to_repo)
    new_filename_relative_to_root = os.path.join(
        "repo_new", filename_relative_to_repo)
    cmd = ["pcpp", filename_relative_to_root, "-o",
           new_filename_relative_to_root, "-I", "repo/include", "-I", "repo/macro"]
    s = EasyProcess(cmd).call().stdout
    print(s)
    return new_filename_relative_to_root


def format_file(filename):
    cmd = ["clang-format", "-style=google", "-i", filename]
    s = EasyProcess(cmd).call().stdout
    print(s)


def mkdir_if_not_exits(dirpath):
    if not os.path.exists(dirpath):
        os.makedirs(dirpath)


def process_file(filename_relative_to_repo):
    new_filename_relative_to_root = replace_file(filename_relative_to_repo)
    format_file(new_filename_relative_to_root)


def process_files_under_dir(dirpath):
    child_paths = os.listdir(os.path.join("repo", dirpath))
    for child_path in child_paths:
        if child_path.endswith('.h') or child_path.endswith('.c') or child_path.endswith('.cpp'):
            filename_relative_to_repo = os.path.join(dirpath, child_path)
            process_file(filename_relative_to_repo)


def setup_dirs():
    mkdir_if_not_exits("repo_new")
    mkdir_if_not_exits(os.path.join("repo_new", "include"))
    mkdir_if_not_exits(os.path.join("repo_new", "src"))
    mkdir_if_not_exits(os.path.join("repo_new", "test"))


setup_dirs()
process_file("src/vector.c")
# process_files_under_dir('include')
# process_files_under_dir('src')
